package customview.ike.com.customviewproject.utils.recycleViewCommonUtils.MultiItemAdapter;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by ike on 2017/9/15.
 * 多条目数据适配器
 */

public class MultiItemTypeAdapter<T> extends RecyclerView.Adapter<MultiItemTypeAdapter.ViewHolder> {
    private final String Tag="MultiItemTypeAdapter";
    private List<T> mData;
    public MultiItemManager<T> manager=new MultiItemManager<>();

    public MultiItemTypeAdapter(List<T> mData) {
        this.mData = mData;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        
        ItemViewDelegate itemViewDelegate = manager.getItemViewDelegate(viewType);
        int layoutId=itemViewDelegate.getItemViewLayoutId();
        View itemView=View.inflate(parent.getContext(),layoutId,null);
        ViewHolder holder=new ViewHolder(itemView);
        
        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        int itemViewType = manager.getItemViewType(mData.get(position), position);
        ItemViewDelegate itemViewDelegate = manager.getItemViewDelegate(itemViewType);
        holder.setBind(itemViewDelegate);
        if (itemClickListener!= null){
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClickListener.onItemClick(mData.get(position),position,holder.itemView);
                }
            });
        }
        itemViewDelegate.convert(holder,mData.get(position),position);
    }

    @Override
    public int getItemCount() {
        if (mData!=null&&mData.size()>0){
            return mData.size();
        }
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        return manager.getItemViewType(mData.get(position),position);
    }
   public static class ViewHolder extends RecyclerView.ViewHolder{

      
       private ViewDataBinding mBind;
        public ViewHolder(View itemView) {
            super(itemView);
            mBind = DataBindingUtil.bind(itemView);
        }
        private void setBind(ItemViewDelegate item){
            item.bind=mBind;
        }
    }
    public void addItemViewDelegate(ItemViewDelegate itemViewDelegate){
        manager.addItemDelegate(itemViewDelegate);
    }

    public void setOnItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    private ItemClickListener itemClickListener;
    public interface ItemClickListener<T>{
        void onItemClick(T item, int position, View view);
    }

}
